<?php


namespace App\Http\Controllers\Saas;


use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Model\Device;
use App\Model\Feedback;
use App\Model\House;
use App\Model\Order;
use App\Model\UserCashLog;
use App\User;
use App\Utils\Result;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller
{
    public function dashboard()
    {
        $data = [
           'house' => [],
           'device' => []
        ];

        // 房源
        $data['house']['total'] = House::query()->count();
        $data['house']['hired'] = House::query()
            ->whereHas('contract', function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
            })
            ->count();
        $data['house']['vacant'] = $data['house']['total'] - $data['house']['hired'];

        // 设备
        $data['device']['total'] = Device::query()->count();
        $data['device']['used'] = Device::query()
            ->where('house_id','>',0)
            ->count();
        $data['device']['online'] = Device::query()->where('online_status', 1)->count();
        $data['device']['offline'] = $data['device']['total'] - $data['device']['online'];

        $data['order'] = [
            'total' => Order::query()->where('status', 3)->sum('pay_amt'),
            'withdraw' => UserCashLog::query()->where('status', '<>', 'F')->sum('cash_amt'),
            'fee' => Order::query()->where('status', 3)->sum('fee'),
        ];
        $data['user_amount'] = User::query()->sum('amount');

        // 问题反馈
        $data['feedback'] = Feedback::query()->count();

        // 用户总数
        $data['user'] = User::query()->count();

        $data['fandong'] = User::query()->whereHas('business', function($q) {
            $q->whereHas('house');
        })->count();
        if(Redis::exists('LOW_POWER_WARNING')){
           $data['low_power'] =  Redis::get('LOW_POWER_WARNING');
        }else{
            $data['low_power'] = 0;
        }
        if(Redis::exists('LOW_DAY_WARNING')){
            $data['low_day'] =  Redis::get('LOW_DAY_WARNING');
        }else{
            $data['low_day'] = 0;
        }
        if(Redis::exists('LOW_CANCEL_WARNING')){
            $data['cancel_power'] =  Redis::get('LOW_CANCEL_WARNING');
        }else{
            $data['cancel_powerr'] = 0;
        }
        return Result::success($data);
    }

    public function setLowData(Request $request){
        $low_power = $request->input('low_power');
        $low_day = $request->input('low_day');
        $cancel_power = $request->input('cancel_power');
        Redis::set('LOW_DAY_WARNING',$low_day);
        Redis::set('LOW_POWER_WARNING',$low_power);
        Redis::set('LOW_CANCEL_WARNING',$cancel_power);
        return Result::success();
    }
}
